package com.egg.demo.secure;

import com.egg.common.util.SecureUtil;
import com.egg.demo.secure.annotation.Decrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;


@Slf4j
@ControllerAdvice
public class DecryptRequestAdvice extends RequestBodyAdviceAdapter {


    @Override
    public boolean supports(MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 当某个接口方法或参数上加了@Decrypt注解，才进行解密操作
        return methodParameter.hasMethodAnnotation(Decrypt.class) || methodParameter.hasParameterAnnotation(Decrypt.class);
    }

    @Override
    public HttpInputMessage beforeBodyRead(
            final HttpInputMessage inputMessage
            , MethodParameter parameter
            , Type targetType, Class<? extends HttpMessageConverter<?>> converterType
    ) throws IOException {
        InputStream inputStream = inputMessage.getBody();
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        String requestBody = new String(bytes);
        try {
            // 结合自己业务针对获取到的requestBody内容进行修改解密等操作
            // 对称秘钥，可以从数据库或缓存中获取，这里暂时写死
            String aes = "对称秘钥凑满32位:12345678";
            // aesDecrypt 内的 getSecretKey(key) 秘钥必须为 32位或者16为，
            // aesDecrypt 内的 getSecureRandomSecretKey(key) 任意秘钥
            String decryptData = SecureUtil.aesDecrypt(aes, requestBody);
            // 把入参修改为解密后的内容
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(decryptData.getBytes());
            return new HttpInputMessage() {
                @Override
                public InputStream getBody() {
                    return byteArrayInputStream;
                }

                @Override
                public HttpHeaders getHeaders() {
                    return inputMessage.getHeaders();
                }
            };
        } catch (Exception e) {
            log.error("解密数据失败", e);
        }
        return super.beforeBodyRead(inputMessage, parameter, targetType, converterType);
    }


}